package concurrency;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 装配工
 */
class Assembler implements Runnable {
    private Car mCar;

    private CarQueue mChassisQueue;

    private CarQueue mFinishingQueue;

    private RobotPool mRobotPool;

    private CyclicBarrier mBarrier = new CyclicBarrier(4);

    public Assembler(CarQueue cq, CarQueue fq, RobotPool rp) {
        mChassisQueue = cq;
        mFinishingQueue = fq;
        mRobotPool = rp;
    }


    public CyclicBarrier barrier() {
        return mBarrier;
    }

    public Car car() {
        return mCar;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                // Blocks until chassis is available:
                mCar = mChassisQueue.take();
                // Hire robots to perform work:
                mRobotPool.hire(EngineRobot.class, this);
                mRobotPool.hire(DriveTrainRobot.class, this);
                mRobotPool.hire(WheelRobot.class, this);
                // Until the robots finish
                mBarrier.await();
                // Put car into finishingQueue for further work
                mFinishingQueue.put(mCar);
            }
        } catch (InterruptedException e) {
            System.out.println("Exiting Assembler via interrupt");
            // e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println("Assembler off");
    }
}
